package com.hyjoy.web.servlet;

import com.hyjoy.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * Created by hyjoy on 2018/4/5.
 */
public class BaseServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取方法名
            String name = req.getParameter("method");
            // 判断参数是否为空，若为空，执行默认的方法
            if (StringUtils.isTrimEmpty(name)) {
                name = "index";
            }
            // 获取方法对象
            Method method = getClass().getMethod(name, HttpServletRequest.class, HttpServletResponse.class);
            // 让方法执行，接受返回
            String path = (String) method.invoke(this, req, resp);
            // 判断返回值是否为空，若不为空统一处理请求转发
            if (path != null) {
                req.getRequestDispatcher(path).forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    /**
     * 默认
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("亲,不要捣乱");
        return null;
    }
}
